<?php
/**
 * Geneone: Content Management Framework
 * Change Password
 *
 * http://geneone.neondragon.net/
 *
 * @package Geneone
 * @author Khlo
 * @version 1.0
 * @copyright 2004-2006 Geneone Development Team
 */
 
class Gene_Special_Settings {
	/**
	 * Default Action
	 */
	function main() {
		$tpl =& Gene::getTemplate();
		$user =& Gene::getUser();
		$auth =& Gene::getAuth();
		
		$tpl->assign ("pagetitle", "Settings");
		$tpl->assign ("email", $user->getEmail());
		$tpl->assign ("finalbody", $tpl->fetch("special/settings/main"));
	}
	
	/**
	 * Change Public Name
	 */
	function name() {
		$user =& Gene::getUser();
		$info = $user->getInfo();
		$tpl =& Gene::getTemplate();
		$tpl->assign ("pagetitle", "Public Name");
		
		$tpl->append("scripts", "register");
		
		if ($_SERVER['REQUEST_METHOD'] == 'POST') {
			$publicname = Gene_Request::getString("publicname", GENE_REQUEST_POST);
			if ($publicname == "!newname!") {
				$newname = Gene_User::canonizePublicName(Gene_Request::getString("newname", GENE_REQUEST_POST));
			} else {
				$newname = Gene_User::canonizePublicName($publicname);
			}
			
			$i = $user->setPublicName($newname);
			if (!PEAR::isError($i)) {
				$tpl->append ("member", array("name" => $newname), true);
				$tpl->assign ("success", true);
			} else {
				$tpl->assign ("errormsg", $i->getMessage());
			}
		}
		
		$publicnames = $user->getAllPublicNames();
		$tpl->assign ("publicnames", $publicnames);
		
		$numnames = $user->getNumberPublicNames();
		$tpl->assign ("numnames", $numnames);
		
		$tpl->assign ("finalbody", $tpl->fetch("special/settings/name"));
	}
	
	/**
	 * Change Password
	 */
	function password() {
		$user =& Gene::getUser();
		$info = $user->getInfo();
		$tpl =& Gene::getTemplate();
		$tpl->assign ("pagetitle", "Change Password");
	
		if ($_SERVER['REQUEST_METHOD'] == 'POST') {
			$oldpw = Gene_Request::getString("currentpw", GENE_REQUEST_POST);
			$newpw = Gene_Request::getString("newpw1", GENE_REQUEST_POST);
			$newpw2 = Gene_Request::getString("newpw2", GENE_REQUEST_POST);
			
			if ($user->checkPassword($oldpw)) {
				if ($newpw == $newpw2) {
					if ($user->setPassword($newpw)) {
						$tpl->assign ("success", true);
					} else {
						$tpl->assign ("errormsg", "Operation failed for unknown reason.");
					}
				} else {
					$tpl->assign ("errormsg", "Please re-type your new password exactly.");
				}
			} else {
				$tpl->assign ("errormsg", "Please ensure you enter your current password exactly to confirm the password change.");
			}
			
			$tpl->assign ("finalbody", $tpl->fetch("special/settings/password"));
		} else {
			$tpl->assign ("finalbody", $tpl->fetch("special/settings/password"));
		}
	}
	
	/**
	 * Change E-Mail Address
	 */
	function email() {
		$user =& Gene::getUser();
		$tpl =& Gene::getTemplate();
		$tpl->assign ("pagetitle", "Change E-Mail Address");

		if ($_SERVER['REQUEST_METHOD'] == 'POST') {
			$password = Gene_Request::getString("password", GENE_REQUEST_POST);
			if ($user->checkPassword($password)) {
				$email = Gene_Request::getEmail("newemail1", GENE_REQUEST_POST);
				$email2 = Gene_Request::getEmail("newemail2", GENE_REQUEST_POST);
				
				if (!$email OR !$email2) {
					$tpl->assign ("errormsg", "You did not enter and confirm your new e-mail address.");
					$tpl->assign ("email", $user->getEmail());
					$tpl->assign ("finalbody", $tpl->fetch("special/settings/email"));
				} else if ($email != $email2) {
					$tpl->assign ("errormsg", "The e-mail addresses you entered did not match.");
					$tpl->assign ("email", $user->getEmail());
					$tpl->assign ("finalbody", $tpl->fetch("special/settings/email"));
				} else {
					$db =& Gene::getDatabase();
					
					// Do we already have a user with this email?
					$q = $db->prepare("SELECT * FROM ".Gene::tableName("users")." WHERE email=?");
					$res = $q->execute(array($email));
					if ($res->numRows()) {
						$tpl->assign ("errormsg", "Someone is already using the e-mail account you specified.");
						$tpl->assign ("email", $user->getEmail());
						$tpl->assign ("finalbody", $tpl->fetch("special/settings/email"));
					} else {
						/* We're good to go. */
						
						// Generate confirmation key
						// We use crc32 because it is a bit easier to type than md5
						srand((double)microtime()*1000000);
						$key = sprintf("%u", crc32(time().$email.Gene::getSetting("gene_name").rand(0,30000)));
					
						$db->extended->autoExecute(
							Gene::tableName("user_email_change"),
							array(
								"user_id" => $user->getUserId(),
								"email" => $email,
								"confirm_key" => $key,
								"timestamp" => time(),
							),
							MDB2_AUTOQUERY_INSERT
						);
						
						/* Send E-Mail */
						$baseurl = Gene::makeLink(Gene::specialID("Settings"))."/email";
						$urlbits = parse_url($baseurl);
						if (isset($urlbits['query'])) {
							$url = $baseurl."&user=".$user->getUserId()."&email=".$email."&confirmcode=".$key;
						} else {
							$url = $baseurl."?user=".$user->getUserId()."&email=".$email."&confirmcode=".$key;
						}
						
						$info = $user->getInfo();				
			
						$message = "This email is being sent to you by ".Gene::getSetting("gene_name")." because someone has requested the e-mail address for ".$info['name']." to be set to ".$email.".\r\nIf you feel you received this email in error, please disregard it.\r\n\r\nTo confirm you wish to change the e-mail address, please log in at the following address:\r\n".Gene::makeLink(Gene::specialID("Login"))."\r\n\r\nThen copy and paste the following address in to your web browser:\r\n".$url."\r\n\r\nPlease confirm this e-mail address change within 7 days - otherwise the request will be cancelled.";
						
						Gene::sendEmail($email, Gene::getSetting("gene_name")." - E-Mail Address Change", $message);
						
						$tpl->assign ("success", true);
						$tpl->assign ("newemail", $email);
						$tpl->assign ("finalbody", $tpl->fetch("special/settings/email"));
					}
				}
			} else {
				$tpl->assign ("errormsg", "Your password was entered incorrectly.");
				$tpl->assign ("email", $user->getEmail());
				$tpl->assign ("finalbody", $tpl->fetch("special/settings/email"));
			}
		} else {
			$cuserid = Gene_Request::getInteger("user", GENE_REQUEST_GET | GENE_REQUEST_POST);
			$email = Gene_Request::getEmail("email", GENE_REQUEST_GET | GENE_REQUEST_POST);
			$code = Gene_Request::getString("confirmcode", GENE_REQUEST_GET | GENE_REQUEST_POST);
			
			if ($cuserid AND $email AND $code) {
				// Check user who wants to change is currently logged in.
				if ($user->getUserId() == $cuserid) {
					$db =& Gene::getDatabase();
					$q = $db->prepare("SELECT * FROM ".Gene::tableName("user_email_change")." WHERE user_id=? AND confirm_key=? AND email=?");
					$res = $q->execute(array($cuserid, $code, $email));
					if ($q = $res->fetchRow()) {
						// Change the e-mail address
						if ($user->setEmail($email)) {
							$tpl->assign ("newemail", $email);
							$tpl->assign ("finalbody", $tpl->fetch("special/settings/emailsuccess"));
						} else {
							// Someone else is using that e-mail address
							$tpl->assign ("errormsg", "Someone is already using the e-mail account you specified.");
							$tpl->assign ("email", $user->getEmail());
							$tpl->assign ("finalbody", $tpl->fetch("special/settings/email"));
						}
						
						// Garbage Collection: Delete requests older than 7 days and all other requests by same user
						$q = $db->prepare ("DELETE FROM ".Gene::tableName("user_email_change")." WHERE timestamp < ? OR user_id=? OR email=?");
						$q->execute(array(time()-604800, $user->getUserId(), $email));
					} else {
						$tpl->assign ("permissionerror", 'Sorry - this e-mail change request has expired for security reasons. Please submit a new one.');
						$tpl->assign ("finalbody", $tpl->fetch("errors/permissionerror"));
					}
				} else {
					$cuser = Gene_User::fromUserID($cuserid);
					$cuserinfo = $cuser->getInfo();
					$tpl->assign ("permissionerror", 'Please <a href="'.Gene::makeLink(Gene::specialID("Login")).'">login</a> as <strong>'.$cuserinfo['name'].'</strong> before continuing with this operation.');
					$tpl->assign ("finalbody", $tpl->fetch("errors/permissionerror"));
				}
			} else {
				$tpl->assign ("email", $user->getEmail());
				$tpl->assign ("finalbody", $tpl->fetch("special/settings/email"));
			}
		}
	}
}

?>